from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from . import brand_serializers
from goods.models import Brand
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client
from django.conf import settings
from goods.models import SKUImage,SKU

# 1.品牌记录
class BrandViewSet(ModelViewSet):
    serializer_class = brand_serializers.BrandViewSerializer
    pagination_class = MyPageNumberPagination
    queryset = Brand.objects.all()

    # 2.重写create方法
    def create(self, request, *args, **kwargs):
        # 1.获取参数
        logo = request.FILES.get("logo")
        name= request.data.get("name")
        first_letter=request.data.get("first_letter")

        # 2.校验参数
        if not all([logo,name,first_letter]):
            return Response(status=403)

        # 3.数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())
        print(ret)

        # 3.1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3.2数据入库图片
        logo_url = ret.get("Remote file_id")
        Brand.objects.create(name=name,logo=logo_url,first_letter=first_letter)


        # 4.返回响应
        return Response(status=201)

    # 3.重写update方法
    def update(self, request, *args, **kwargs):
        pk = self.kwargs.get("pk")
        logo = request.FILES.get("logo")
        name = request.data.get("name")
        first_letter = request.data.get("first_letter")

        # 2.校验参数
        if not all([logo, name, first_letter]):
            return Response(status=403)

        # 3.数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(logo.read())

        # 3.1判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)

        # 3.2数据入库图片
        logo_url = ret.get("Remote file_id")
        Brand.objects.filter(pk=pk).update(name=name,logo=logo_url,first_letter=first_letter)

        # 4.返回响应
        return Response(status=201)
        # SKUImage.objects.filter(id=sku_image.id).update(sku_id =sku_id,image=image_url)